<?php
namespace app\controllers;

use app\models\BlockRecorder;

class BlockController extends BaseController{
    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['BlockRecorder']['id']);
        if($id){
            $model = BlockRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }
        }else{
            $model = new BlockRecorder();
            $model->addtime = time();
        }
        $result = $model->add($post);
        return json_encode($result);
    }

    public function actionList(){
        $list = BlockRecorder::find()->asArray()->all();
        foreach($list as $k=>$v){
            $v['pics'] = json_decode($v['pics'],true);
            $arr=[];
            foreach($v['pics'] as $pv){
                $arr[]=str_replace('../',\Yii::$app->params['pic_url'],$pv);
            }
            $list[$k]['pics'] = $arr;
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $list[$k]['thumb_pic'] = empty($v['thumb_pic'])?"":str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = BlockRecorder::find()->where('id=:id',[':id' => $id])->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model['pics'] = empty($model['pics'])?[]:json_decode($model['pics'],true);
        $arr=[];
        foreach($model['pics'] as $p){
            $arr[]=str_replace("../",\Yii::$app->params['pic_url'],$p);
        }
        $model['pics'] = $arr;
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    public function actionDel(){
        $id = \Yii::$app->request->post('id');
        $model = BlockRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model->delete();
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }

}
